import React, { useState } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Statistic, 
  Progress, 
  Button, 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  Avatar,
  Upload,
  Spin,
  Tag,
  Modal
} from 'antd';
import { 
  UserOutlined, 
  MailOutlined, 
  PhoneOutlined, 
  CalendarOutlined, 
  EditOutlined, 
  SaveOutlined, 
  UploadOutlined,
  ManOutlined,
  WomanOutlined,
  IdcardOutlined,
  CheckCircleOutlined,
  SafetyOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  GlobalOutlined,
  CloseCircleOutlined,
  StarOutlined,
  LockOutlined
} from '@ant-design/icons';
import { motion } from 'framer-motion';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import { userApi } from '../../services/userApi';
import { notification } from '../common';
import dayjs from 'dayjs';

interface PersonalDetailsProps {
  userProfile: {
    email?: string;
    phone?: string;
    location?: string;
    created_at?: string;
    updated_at?: string;
    last_login?: string;
    department?: string;
    employee_id?: string;
    language?: string;
    timezone?: string;
    bio?: string;
    skills?: string[];
    is_active?: boolean;
    is_verified?: boolean;
    is_superuser?: boolean;
    login_count?: number;
    profile_completion?: number;
  };
  onUpdate?: (data: any) => void;
}

const PersonalDetailCard: React.FC<PersonalDetailsProps> = ({ userProfile, onUpdate }) => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [isEditing, setIsEditing] = useState(false);
  const [activeTab, setActiveTab] = useState<'basic' | 'security' | 'activity'>('basic');
  const [form] = Form.useForm();

  // 计算资料完整度
  const calculateCompletion = () => {
    // 定义所有需要检查的字段
    const fields = ['email', 'phone', 'location', 'bio', 'department', 'employee_id'];
    // 过滤出非空且非空字符串的字段
    const filledFields = fields.filter(field => {
      const value = userProfile[field as keyof typeof userProfile];
      return value !== undefined && value !== null && value !== '';
    });
    // 计算完成度百分比
    return Math.round((filledFields.length / fields.length) * 100);
  };

  const calculatedCompletion = calculateCompletion();
  const profileCompletion = userProfile.profile_completion ?? calculatedCompletion;
  
  // 处理编辑表单提交
  const handleEditSubmit = async (values: any) => {
    try {
      if (onUpdate) {
        await onUpdate(values);
        notification.success({
          title: '操作成功',
          message: '信息更新成功'
        });
      }
      setIsEditing(false);
    } catch (error) {
      notification.error({
        title: '操作失败',
        message: '更新失败，请重试'
      });
    }
  };

  // 信息项组件
  const InfoItem = ({ icon, label, value, isTag = false, tagColor }: any) => (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      padding: '12px 16px',
      borderRadius: '8px',
      background: `linear-gradient(135deg, ${theme.cardBackground}00 0%, ${theme.cardBackground}20 100%)`,
      marginBottom: '12px',
      transition: 'all 0.3s ease',
      cursor: 'pointer',
      border: `1px solid ${theme.cardBorder}20`,
    }}
    onMouseEnter={(e) => {
      e.currentTarget.style.transform = 'translateX(5px)';
      e.currentTarget.style.background = `linear-gradient(135deg, ${theme.glowColor}10 0%, ${theme.cardBackground}30 100%)`;
      e.currentTarget.style.borderColor = `${theme.glowColor}40`;
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.transform = 'translateX(0)';
      e.currentTarget.style.background = `linear-gradient(135deg, ${theme.cardBackground}00 0%, ${theme.cardBackground}20 100%)`;
      e.currentTarget.style.borderColor = `${theme.cardBorder}20`;
    }}>
      <div style={{
        fontSize: '18px',
        color: theme.glowColor,
        marginRight: '12px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: '32px',
        height: '32px',
        borderRadius: '8px',
        background: `${theme.glowColor}15`
      }}>
        {icon}
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: '12px', color: theme.textSecondary, marginBottom: '2px' }}>
          {label}
        </div>
        {isTag ? (
          <Tag color={tagColor} style={{ margin: 0 }}>{value || '未设置'}</Tag>
        ) : (
          <div style={{
            fontSize: '14px',
            color: value ? theme.textPrimary : theme.textSecondary,
            fontWeight: value ? '500' : '400'
          }}>
            {value || '未设置'}
          </div>
        )}
      </div>
    </div>
  );

  // 标签页样式
  const tabStyle = (isActive: boolean) => ({
    padding: '8px 20px',
    borderRadius: '20px',
    background: isActive ? `linear-gradient(135deg, ${theme.glowColor} 0%, ${theme.glowColor}dd 100%)` : 'transparent',
    color: isActive ? '#fff' : theme.textSecondary,
    cursor: 'pointer',
    transition: 'all 0.3s ease',
    marginRight: '8px',
    fontSize: '14px',
    fontWeight: isActive ? '600' : '400',
    border: isActive ? 'none' : `1px solid ${theme.cardBorder}40`,
  });

  return (
    <>
      <Card
        style={{
          background: theme.cardBackground,
          borderRadius: '16px',
          border: `1px solid ${theme.cardBorder}`,
          boxShadow: theme.cardShadow,
          overflow: 'hidden',
          backdropFilter: 'blur(10px)',
          position: 'relative',
        }}
        styles={{
          body: { padding: '24px' }
        }}
      >
        {/* 背景装饰 */}
        <div style={{
          position: 'absolute',
          top: '-50px',
          right: '-50px',
          width: '200px',
          height: '200px',
          borderRadius: '50%',
          background: `radial-gradient(circle, ${theme.glowColor}20 0%, transparent 70%)`,
          filter: 'blur(40px)',
          pointerEvents: 'none',
        }} />

        {/* 头部 */}
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '24px'
        }}>
          <h2 style={{
            color: theme.textPrimary,
            fontSize: '20px',
            fontWeight: 'bold',
            margin: 0,
            display: 'flex',
            alignItems: 'center',
          }}>
            <IdcardOutlined style={{ marginRight: '8px', color: theme.glowColor }} />
            详细信息
          </h2>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => setIsEditing(true)}
            style={{
              color: theme.glowColor,
              background: `${theme.glowColor}10`,
              border: 'none',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = `${theme.glowColor}20`;
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = `${theme.glowColor}10`;
            }}
          >
            编辑
          </Button>
        </div>

        {/* 资料完整度 */}
        <div style={{
          marginBottom: '24px',
          padding: '16px',
          borderRadius: '12px',
          background: `linear-gradient(135deg, ${theme.glowColor}05 0%, ${theme.glowColor}10 100%)`,
          border: `1px solid ${theme.cardBorder}20`,
          backdropFilter: 'blur(10px)',
        }}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            marginBottom: '8px'
          }}>
            <span style={{ color: theme.textSecondary, fontSize: '13px' }}>资料完整度</span>
            <span style={{
              color: theme.glowColor,
              fontSize: '14px',
              fontWeight: 'bold'
            }}>{profileCompletion}%</span>
          </div>
          <Progress
            percent={profileCompletion}
            showInfo={false}
            strokeColor={{
              '0%': theme.glowColor,
              '100%': `${theme.glowColor}aa`,
            }}
            trailColor={`${theme.cardBorder}40`}
            size="small"
            strokeLinecap="round"
          />
          <div style={{
            marginTop: '8px',
            fontSize: '12px',
            color: theme.textSecondary
          }}>
            {profileCompletion < 100 ? (
              <span>完善资料可获得更好的使用体验</span>
            ) : (
              <span style={{ color: theme.glowColor, fontWeight: '500' }}>
                <CheckCircleOutlined style={{ marginRight: '4px' }} />
                资料已完善
              </span>
            )}
          </div>
        </div>

        {/* 标签页 */}
        <div style={{
          display: 'flex',
          marginBottom: '20px',
          borderBottom: `1px solid ${theme.cardBorder}20`,
          paddingBottom: '12px'
        }}>
          <div
            style={tabStyle(activeTab === 'basic')}
            onClick={() => setActiveTab('basic')}
            onMouseEnter={(e) => {
              if (activeTab !== 'basic') {
                e.currentTarget.style.background = `${theme.glowColor}10`;
              }
            }}
            onMouseLeave={(e) => {
              if (activeTab !== 'basic') {
                e.currentTarget.style.background = 'transparent';
              }
            }}
          >
            <UserOutlined style={{ marginRight: '4px' }} />
            基本信息
          </div>
          <div
            style={tabStyle(activeTab === 'security')}
            onClick={() => setActiveTab('security')}
            onMouseEnter={(e) => {
              if (activeTab !== 'security') {
                e.currentTarget.style.background = `${theme.glowColor}10`;
              }
            }}
            onMouseLeave={(e) => {
              if (activeTab !== 'security') {
                e.currentTarget.style.background = 'transparent';
              }
            }}
          >
            <SafetyOutlined style={{ marginRight: '4px' }} />
            安全状态
          </div>
          <div
            style={tabStyle(activeTab === 'activity')}
            onClick={() => setActiveTab('activity')}
            onMouseEnter={(e) => {
              if (activeTab !== 'activity') {
                e.currentTarget.style.background = `${theme.glowColor}10`;
              }
            }}
            onMouseLeave={(e) => {
              if (activeTab !== 'activity') {
                e.currentTarget.style.background = 'transparent';
              }
            }}
          >
            <ClockCircleOutlined style={{ marginRight: '4px' }} />
            活动记录
          </div>
        </div>

        {/* 内容区域 */}
        <div style={{ minHeight: '300px' }}>
          {activeTab === 'basic' && (
            <div className="fade-in">
              <InfoItem
                icon={<MailOutlined />}
                label="邮箱地址"
                value={userProfile.email}
              />
              <InfoItem
                icon={<PhoneOutlined />}
                label="联系电话"
                value={userProfile.phone}
              />
              <InfoItem
                icon={<EnvironmentOutlined />}
                label="所在地区"
                value={userProfile.location}
              />
              <InfoItem
                icon={<TeamOutlined />}
                label="所属部门"
                value={userProfile.department}
              />
              <InfoItem
                icon={<IdcardOutlined />}
                label="员工编号"
                value={userProfile.employee_id}
              />
              <InfoItem
                icon={<GlobalOutlined />}
                label="语言偏好"
                value={userProfile.language || '中文'}
              />
            </div>
          )}

          {activeTab === 'security' && (
            <div className="fade-in">
              <InfoItem
                icon={userProfile.is_active ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                label="账户状态"
                value={userProfile.is_active ? '活跃' : '已禁用'}
                isTag={true}
                tagColor={userProfile.is_active ? 'success' : 'error'}
              />
              <InfoItem
                icon={userProfile.is_verified ? <SafetyOutlined /> : <CloseCircleOutlined />}
                label="验证状态"
                value={userProfile.is_verified ? '已验证' : '未验证'}
                isTag={true}
                tagColor={userProfile.is_verified ? 'blue' : 'default'}
              />
              <InfoItem
                icon={<StarOutlined />}
                label="权限等级"
                value={userProfile.is_superuser ? '超级管理员' : '普通用户'}
                isTag={true}
                tagColor={userProfile.is_superuser ? 'gold' : 'default'}
              />
              <InfoItem
                icon={<LockOutlined />}
                label="登录次数"
                value={userProfile.login_count ? `${userProfile.login_count} 次` : '0 次'}
              />
            </div>
          )}

          {activeTab === 'activity' && (
            <div className="fade-in">
              <InfoItem
                icon={<CalendarOutlined />}
                label="注册时间"
                value={userProfile.created_at ? dayjs(userProfile.created_at).format('YYYY-MM-DD HH:mm') : undefined}
              />
              <InfoItem
                icon={<ClockCircleOutlined />}
                label="最后更新"
                value={userProfile.updated_at ? dayjs(userProfile.updated_at).format('YYYY-MM-DD HH:mm') : undefined}
              />
              <InfoItem
                icon={<UserOutlined />}
                label="最近登录"
                value={userProfile.last_login ? dayjs(userProfile.last_login).format('YYYY-MM-DD HH:mm') : '从未登录'}
              />
              <InfoItem
                icon={<GlobalOutlined />}
                label="时区设置"
                value={userProfile.timezone || 'Asia/Shanghai'}
              />
            </div>
          )}
        </div>

        {/* 技能标签 */}
        {userProfile.skills && userProfile.skills.length > 0 && (
          <div style={{
            marginTop: '24px',
            padding: '16px',
            borderRadius: '12px',
            background: `${theme.cardBackground}40`,
            border: `1px solid ${theme.cardBorder}20`,
          }}>
            <div style={{
              fontSize: '14px',
              color: theme.textSecondary,
              marginBottom: '12px',
              fontWeight: '500'
            }}>
              技能标签
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {userProfile.skills.map((skill, index) => (
                <Tag
                  key={index}
                  style={{
                    padding: '4px 12px',
                    borderRadius: '16px',
                    background: `linear-gradient(135deg, ${theme.glowColor}20 0%, ${theme.glowColor}10 100%)`,
                    border: `1px solid ${theme.glowColor}40`,
                    color: theme.glowColor,
                    cursor: 'pointer',
                    transition: 'all 0.3s ease',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.transform = 'scale(1.05)';
                    e.currentTarget.style.background = `linear-gradient(135deg, ${theme.glowColor}30 0%, ${theme.glowColor}20 100%)`;
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = 'scale(1)';
                    e.currentTarget.style.background = `linear-gradient(135deg, ${theme.glowColor}20 0%, ${theme.glowColor}10 100%)`;
                  }}
                >
                  {skill}
                </Tag>
              ))}
            </div>
          </div>
        )}
      </Card>

      {/* 编辑弹窗 */}
      <Modal
        title="编辑个人信息"
        open={isEditing}
        onCancel={() => setIsEditing(false)}
        onOk={() => form.submit()}
        width={600}
        style={{ top: 20 }}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={userProfile}
          onFinish={handleEditSubmit}
        >
          <Form.Item name="email" label="邮箱地址">
            <Input prefix={<MailOutlined />} placeholder="请输入邮箱地址" />
          </Form.Item>
          <Form.Item name="phone" label="联系电话">
            <Input prefix={<PhoneOutlined />} placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item name="location" label="所在地区">
            <Input prefix={<EnvironmentOutlined />} placeholder="请输入所在地区" />
          </Form.Item>
          <Form.Item name="department" label="所属部门">
            <Input prefix={<TeamOutlined />} placeholder="请输入所属部门" />
          </Form.Item>
          <Form.Item name="employee_id" label="员工编号">
            <Input prefix={<IdcardOutlined />} placeholder="请输入员工编号" />
          </Form.Item>
          <Form.Item name="bio" label="个人简介">
            <Input.TextArea rows={4} placeholder="请输入个人简介" />
          </Form.Item>
        </Form>
      </Modal>

      <style>{`
        .fade-in {
          animation: fadeIn 0.5s ease-in;
        }
        
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </>
  );
};

export default PersonalDetailCard;